<template>
  <div class="page praticle-page flex-col">
    <div class="box_1 flex-row">
      <div class="group_1 ">
        <img class="label_4" src="@/assets/ide/liebiao.png" />
        <span>{{ examTitle ? examTitle : '精选题库' }}</span>
        <el-countdown v-if="examEndTime && new Date() < new Date(examEndTime)" class="exam-time-countdown"
          @finish="handleCountdownFinish" title="距离竞赛结束还有:" :value="new Date(examEndTime)" />
      </div>
      <div class="group_2">
        <el-button type="primary" plain @click="submitQuestion">提交代码</el-button>
        <el-tooltip
          effect="dark"
          content="通过AI大模型能力进行判题，并会根据你的代码提供一些算法优化建议。（竞赛模式下AI功能禁用）"
          placement="top"
        >
          <el-button v-if="!examId" type="success" plain @click="submitQuestionByAi" :loading="aiJudgingLoading">
            <span v-if="!aiJudgingLoading">AI判题</span>
            <span v-else>AI判题中...</span>
          </el-button>
        </el-tooltip>
      </div>
      <span class="ide-back" @click="goBack()">返回</span>
    </div>
    <div class="box_8 flex-col">
      <div class="group_12 flex-row justify-between">
        <div class="image-wrapper_1 flex-row">
          <img class="thumbnail_2" src="@/assets/ide/xiaobiaoti.png" />
          <div class="question-nav">
            <span>题目描述</span>
          </div>
          <div class="navigation-container">
            <div class="question-nav nav-btn" @click="preQuestion">
              <el-icon><ArrowLeft /></el-icon>
              <span>上一题</span>
            </div>
            <div class="nav-divider"></div>
            <div class="question-nav nav-btn" @click="nextQuestion">
              <el-icon><ArrowRight /></el-icon>
              <span>下一题</span>
            </div>
          </div>
          
          <!-- 仅在非竞赛模式下显示AI题目推荐 -->
          <template v-if="!examId">
            <div class="nav-divider"></div>
            <div class="ai-recommendation-container">
              <el-tooltip
                class="ai-tooltip"
                effect="dark"
                content="AI推荐与本题相似题目，试试看AI给你的推荐题检测此算法掌握程度吧！"
                placement="top"
              >
                <el-button 
                  type="success" 
                  size="small" 
                  class="ai-recommendation-btn" 
                  @click="getSimilarQuestion"
                  :loading="similarLoading"
                >
                  <el-icon class="rec-icon"><Connection /></el-icon>
                  <span>AI题目推荐</span>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </div>
        <div class="image-wrapper_2 flex-row">
          <img class="image_1" src="@/assets/ide/daima.png" />
          代码
        </div>
      </div>
      <div class="group_13 flex-row justify-between">
        <div class="box_3 flex-col">
          <span class="question-title">{{ questionDetail.title }}</span>
          <span class="question-limit">
            <div v-if="questionDetail.difficulty === 1">题目难度：简单 时间限制：{{ questionDetail.timeLimit }} ms 空间限制：{{
              questionDetail.spaceLimit }} 字节</div>
            <div v-if="questionDetail.difficulty === 2">题目难度：中等 时间限制：{{ questionDetail.timeLimit }} ms 空间限制：{{
              questionDetail.spaceLimit }} 字节</div>
            <div v-if="questionDetail.difficulty === 3">题目难度：困难 时间限制：{{ questionDetail.timeLimit }} ms 空间限制：{{
              questionDetail.spaceLimit }} 字节</div>
          </span>
          <span class="question-content" v-html="questionDetail.content"></span>
        </div>
        <div class="group_14 flex-col">
          <div class="group_8 flex-col">
            <codeEditor ref="defaultCodeRef" @update:value="handleEditorContent">
            </codeEditor>
          </div>
          <div class="code-result flex-row">
            <img class="code-result-image" src="@/assets/ide/codeResult.png" />
            <span class="code-result-content">执行结果</span>
          </div>
          <div class="result-container">
            <div class="result-header">
              <span class="result-status red" v-if="userQuestionResultVO.pass === 0">未通过</span>
              <span class="result-status success" v-if="userQuestionResultVO.pass === 1">通过</span>
              <span class="result-status warning" v-if="userQuestionResultVO.pass === 2">请先执行代码</span>
              <span class="result-status info" v-if="userQuestionResultVO.pass === 3">系统正在处理您的代码，请稍后</span>
            </div>
            
            <!-- 未通过情况：显示错误信息和查看详情按钮 -->
            <div v-if="userQuestionResultVO.pass === 0" class="fail-result">
              <div class="error-info" v-if="userQuestionResultVO.exeMessage">
                <div class="error-header">
                  <div class="error-title">异常信息:</div>
                  <el-button 
                    v-if="userQuestionResultVO.userExeResultList && userQuestionResultVO.userExeResultList.length > 0"
                    type="danger" 
                    size="small" 
                    @click="showBadCaseDialog"
                    class="error-view-btn"
                  >
                    查看未通过用例
                  </el-button>
                </div>
                <div class="error-message">
                  <div class="error-text" :class="{'error-text-truncated': isMessageTruncated}">{{ userQuestionResultVO.exeMessage }}</div>
                  <el-button 
                    v-if="isMessageTruncated"
                    type="info" 
                    size="small" 
                    @click="showFullContent(userQuestionResultVO.exeMessage, '完整错误信息')"
                    class="show-more-btn"
                  >
                    查看完整错误信息
                  </el-button>
                </div>
              </div>
              
              <div class="fail-summary" v-if="userQuestionResultVO.userExeResultList && userQuestionResultVO.userExeResultList.length > 0 && !userQuestionResultVO.exeMessage">
                <div class="summary-text">未通过所有测试用例</div>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="showBadCaseDialog"
                  class="view-details-btn"
                >
                  查看未通过用例
                </el-button>
              </div>
            </div>
            
            <!-- 通过情况：使用表格展示测试用例 -->
            <div v-if="userQuestionResultVO.pass === 1 && userQuestionResultVO.userExeResultList && userQuestionResultVO.userExeResultList.length > 0" class="success-result">
              <div class="success-table">
                <el-table 
                  :data="userQuestionResultVO.userExeResultList" 
                  stripe 
                  size="small" 
                  border
                  max-height="300"
                  :header-cell-style="tableHeaderStyle">
                  <el-table-column prop="index" label="测试用例" width="100" fixed="left">
                    <template #default="scope">
                      测试用例 #{{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="input" label="输入" min-width="180" show-overflow-tooltip>
                    <template #default="scope">
                      <div class="cell-content" @click="showFullContent(scope.row.input, '输入')">
                        {{ scope.row.input }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="output" label="预期输出" min-width="180" show-overflow-tooltip>
                    <template #default="scope">
                      <div class="cell-content" @click="showFullContent(scope.row.output, '预期输出')">
                        {{ scope.row.output }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="exeOutput" label="实际输出" min-width="180" show-overflow-tooltip>
                    <template #default="scope">
                      <div class="cell-content" @click="showFullContent(scope.row.exeOutput, '实际输出')">
                        {{ scope.row.exeOutput }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="状态" width="80" fixed="right">
                    <template #default="scope">
                      <el-tag size="small" type="success">通过</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            
            <!-- 处理中或未提交状态显示 -->
            <div v-if="userQuestionResultVO.pass === 2 || userQuestionResultVO.pass === 3" class="empty-result">
              <div v-if="userQuestionResultVO.pass === 3" class="loading-icon">
                <el-icon><Loading /></el-icon>
              </div>
              <div class="empty-text">{{ userQuestionResultVO.pass === 3 ? '正在处理您的代码，请稍候...' : '请先提交代码查看结果' }}</div>
            </div>
          </div>
          
          <!-- 未通过测试用例详情对话框 -->
          <el-dialog
            v-model="badCaseDialogVisible"
            title="未通过测试用例详情"
            width="65%"
            :close-on-click-modal="true"
            destroy-on-close
          >
            <div class="bad-cases-container">
              <div 
                v-for="(item, index) in userQuestionResultVO.userExeResultList" 
                :key="index"
                class="bad-case-card"
                :class="{'case-failed': item.exeOutput !== item.output}"
              >
                <div class="case-header">
                  <div class="case-number">测试用例 #{{ index + 1 }}</div>
                  <div class="case-status">
                    <el-tag size="small" :type="item.exeOutput === item.output ? 'success' : 'danger'">
                      {{ item.exeOutput === item.output ? '通过' : '失败' }}
                    </el-tag>
                  </div>
                </div>
                
                <div class="case-content">
                  <div class="case-row">
                    <div class="row-label">输入:</div>
                    <div class="row-value input-value">{{ item.input }}</div>
                  </div>
                  
                  <div class="case-row">
                    <div class="row-label">预期输出:</div>
                    <div class="row-value">{{ item.output }}</div>
                  </div>
                  
                  <div class="case-row">
                    <div class="row-label">实际输出:</div>
                    <div class="row-value" :class="{'output-error': item.exeOutput !== item.output}">
                      {{ item.exeOutput }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" @click="badCaseDialogVisible = false">关闭</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>
    
    <!-- AI判题结果对话框 -->
    <el-dialog
      v-model="aiDialogVisible"
      :title="aiResultData.isSuccess ? 'AI检测通过' : 'AI检测未通过'"
      width="75%"
      :close-on-click-modal="false"
      class="ai-result-dialog"
      top="5vh"
      :before-close="() => aiDialogVisible = false"
    >
      <div class="ai-result-content">
        <div class="ai-result-header" :class="{'success': aiResultData.isSuccess, 'failure': !aiResultData.isSuccess}">
          <i class="el-icon" :class="aiResultData.isSuccess ? 'el-icon-success' : 'el-icon-error'"></i>
          <span>{{ aiResultData.isSuccess ? '代码通过AI检测' : 'AI检测未通过' }}</span>
          <div class="error-message" v-if="!aiResultData.isSuccess && aiResultData.exeMessage">
            {{ aiResultData.exeMessage }}
          </div>
        </div>

        <div v-if="processAiMessage(aiResultData.message).content" class="ai-analysis-section">
          <div class="section-title">
            <i class="el-icon-info"></i>
            <span>AI代码分析</span>
          </div>
          <div class="ai-text-content" v-html="formatAiContent(processAiMessage(aiResultData.message).content)"></div>
        </div>
        
        <div v-if="processAiMessage(aiResultData.message).codes.length > 0" class="ai-code-blocks">
          <div class="section-title">
            <i class="el-icon-document"></i>
            <span>优化建议代码</span>
          </div>
          <div v-for="(code, index) in processAiMessage(aiResultData.message).codes" :key="index" class="code-block">
            <div class="code-title">示例代码</div>
            <pre class="code-content"><code>{{code}}</code></pre>
            <el-button 
              type="primary" 
              size="small" 
              class="copy-code-btn" 
              @click="copyCode(code)"
            >
              复制代码
            </el-button>
          </div>
        </div>

        <div v-if="aiResultData.score !== undefined" class="ai-score-section">
          <div class="section-title">
            <i class="el-icon-star-on"></i>
            <span>代码评分</span>
          </div>
          <div class="score-display">
            <el-progress 
              type="dashboard" 
              :percentage="aiResultData.score" 
              :color="getScoreColor(aiResultData.score)"
              :stroke-width="12">
            </el-progress>
            <div class="score-text">
              <span>得分: {{ aiResultData.score }}</span>
              <div class="score-comment">{{ getScoreComment(aiResultData.score) }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="aiDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- AI推荐相似题目的加载对话框 -->
    <el-dialog
      v-model="similarLoadingDialogVisible"
      title="AI推荐相似题目"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      center
      class="similar-loading-dialog"
    >
      <div class="loading-content">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p class="loading-text">AI正在推荐相似题目...</p>
        <p class="loading-subtext">正在分析当前题目特征，查找相似算法题目</p>
      </div>
    </el-dialog>
    
    <!-- 无相似题目的提示对话框 -->
    <el-dialog
      v-model="noSimilarQuestionDialogVisible"
      title="没有找到相似题目"
      width="40%"
      :close-on-click-modal="true"
      center
      class="no-similar-dialog"
    >
      <div class="no-similar-content">
        <el-icon class="info-icon"><InfoFilled /></el-icon>
        <p class="info-title">当前题库没有与这道题相似的推荐题目</p>
        <div class="info-reasons">
          <p>可能是因为：</p>
          <ul>
            <li>当前题目特性较为独特</li>
            <li>您可以尝试完成更多题目，以便AI更好地了解您的学习情况</li>
          </ul>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="noSimilarQuestionDialogVisible = false">我知道了</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 在对话框区域添加内容全文查看对话框 -->
    <el-dialog
      v-model="fullContentDialogVisible"
      :title="fullContentTitle"
      width="60%"
      :close-on-click-modal="true"
      destroy-on-close
      class="full-content-dialog"
    >
      <div class="full-content-container">
        <pre class="full-content-text">{{ fullContentText }}</pre>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="fullContentDialogVisible = false">关闭</el-button>
          <el-button type="success" @click="copyFullContent">复制内容</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onBeforeUnmount, onMounted, computed } from "vue"
import codeEditor from "@/components/CodeEditor.vue"
import { ArrowLeft, ArrowRight, Connection, Loading, InfoFilled } from '@element-plus/icons-vue'
import { useRoute } from "vue-router"
import { getQuestionDetailService, preQuestionService, nextQuestionService, getQuestionResultService, getSimilarQuestionService } from "@/apis/question"
import router from "@/router"
import { examNextQuestionService, examPreQuestionService, getExamFirstQuestionService } from "@/apis/exam"
import { ElMessage, ElMessageBox, ElLoading } from "element-plus"
import { userSubmitService, userSubmitByAiService } from "@/apis/user"

function goBack() {
  router.go(-1);
}
const questionDetail = reactive({})
const defaultCodeRef = ref()

let questionId = useRoute().query.questionId
let examId = useRoute().query.examId
let examTitle = useRoute().query.examTitle
let examEndTime = useRoute().query.examEndTime

console.log('examTitle: ', examTitle)
console.log('questionId: ', questionId)

// 使用onMounted确保组件挂载后加载题目数据
onMounted(() => {
  console.log('Component mounted, fetching question details...')
  getQuestionDetail()
})

async function getQuestionDetail() {
  try {
    console.log('Fetching question details...')
    if (examId && (questionId == null || questionId == '')) {
      const eqrs = await getExamFirstQuestionService(examId)
      questionId = eqrs.data
      console.log('qId from exam: ', questionId)
    }
    
    if (!questionId) {
      console.error('No question ID available')
      ElMessage.error('题目ID不存在')
      return
    }
    
    console.log('Fetching details for question ID:', questionId)
    const res = await getQuestionDetailService(questionId)
    console.log('Question details response:', res)
    
    if (res && res.data) {
      Object.assign(questionDetail, res.data)
      console.log('Question details loaded:', questionDetail)
      
      if (defaultCodeRef.value) {
        defaultCodeRef.value.setAceCode(questionDetail.defaultCode)
      } else {
        console.error('defaultCodeRef is not available')
      }
    } else {
      console.error('Empty response or no data in response')
      ElMessage.error('获取题目详情失败')
    }
  } catch (error) {
    console.error('Error fetching question details:', error)
    ElMessage.error('获取题目详情失败，请检查网络连接')
  }
}

async function preQuestion() {
  if (examId) {
    //竞赛中上一题的逻辑  需要提供一个竞赛中获取上一题的接口
    const res = await examPreQuestionService(examId, questionId)
    questionId = res.data
  } else {
    const res = await preQuestionService(questionId)
    questionId = res.data
  }
  getQuestionDetail()
}

async function nextQuestion() {
  if (examId) {
    //竞赛中下一题的逻辑 需要提供一个竞赛中获取下一题的接口
    const res = await examNextQuestionService(examId, questionId)
    questionId = res.data
  } else {
    const res = await nextQuestionService(questionId)
    questionId = res.data
  }
  getQuestionDetail()
}

const similarLoading = ref(false)
const similarLoadingDialogVisible = ref(false)
const noSimilarQuestionDialogVisible = ref(false)

async function getSimilarQuestion() {
  if (similarLoading.value) return
  
  try {
    similarLoading.value = true
    similarLoadingDialogVisible.value = true
    
    const res = await getSimilarQuestionService(questionId)
    
    // 检查返回数据是否有效
    if (!res || res.data === undefined) {
      ElMessage.error('获取推荐题目失败，服务返回空数据')
      return
    }
    
    console.log('Similar question response:', res.data)
    
    // 如果推荐成功，跳转到推荐题目
    if (res.data && res.data !== '0') {
      questionId = res.data
      getQuestionDetail()
      ElMessage({
        message: '已为您找到相似题目，正在跳转...',
        type: 'success',
        duration: 2000
      })
    } else {
      // 无法推荐相似题目时显示对话框
      noSimilarQuestionDialogVisible.value = true
    }
  } catch (error) {
    console.error('Failed to get similar question:', error)
    ElMessage.error('获取推荐题目失败，请稍后重试')
  } finally {
    similarLoading.value = false
    similarLoadingDialogVisible.value = false
  }
}

function handleCountdownFinish() {
  ElMessage.info('竞赛已经结束了哦')
  router.push('/c-oj/home/exam')
}

const submitDTO = reactive({
  examId:'',
  questionId:'',
  programType: 0,
  userCode: ''
})

function handleEditorContent(content) {
  submitDTO.userCode = content
}

const userQuestionResultVO = ref({
  pass: 2,  //默认值为2，未提交代码
  exeMessage: '',
  userExeResultList: [],
})

const pollingInterval = ref(null);
let currentTime

function startPolling() {
  stopPolling(); // 停止之前的轮询
  pollingInterval.value = setInterval(() => {
    getQuestionResult();
  }, 2000); // 每隔2秒请求一次
}

function stopPolling() {
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value);
    pollingInterval.value = null;
  }
}

async function submitQuestion() {
  submitDTO.examId = examId
  submitDTO.questionId = questionId
  await userSubmitService(submitDTO)
  currentTime = new Date().toLocaleString();
  userQuestionResultVO.value.pass = 3
  startPolling()
  
  // 在结果加载完成后，检测是否需要水平滚动
  setTimeout(() => {
    checkScrollNeeded()
  }, 2500)
}

// AI判题加载状态
const aiJudgingLoading = ref(false)
// AI判题加载提示文本
const aiJudgingText = ref('AI正在判题中')
// 加载动画定时器
const aiLoadingTimer = ref(null)
// AI判题阶段
const aiJudgingPhases = [
  '代码分析中',
  '编译执行中',
  '性能评估中',
  '生成优化建议',
  '正在完成判题'
]
const currentPhaseIndex = ref(0)

// 开始加载动画
function startAiLoadingAnimation() {
  // 清除可能存在的定时器
  stopAiLoadingAnimation()
  
  // 设置初始文本和阶段
  currentPhaseIndex.value = 0
  updateLoadingText()
  
  // 创建定时器，每隔800毫秒更新一次文本的点
  let dots = 0
  aiLoadingTimer.value = setInterval(() => {
    dots = (dots + 1) % 4
    
    // 每5秒更新一次阶段
    if (dots === 0) {
      currentPhaseIndex.value = (currentPhaseIndex.value + 1) % aiJudgingPhases.length
    }
    
    updateLoadingText(dots)
  }, 800)
}

// 更新加载文本
function updateLoadingText(dots = 0) {
  const phase = aiJudgingPhases[currentPhaseIndex.value]
  aiJudgingText.value = `AI正在${phase}` + '.'.repeat(dots)
}

// 停止加载动画
function stopAiLoadingAnimation() {
  if (aiLoadingTimer.value) {
    clearInterval(aiLoadingTimer.value)
    aiLoadingTimer.value = null
  }
}

// 组件销毁前清除定时器
onBeforeUnmount(() => {
  stopAiLoadingAnimation()
})

async function submitQuestionByAi() {
  submitDTO.examId = examId
  submitDTO.questionId = questionId
  
  // 设置按钮为加载状态
  aiJudgingLoading.value = true
  // 开始加载动画
  startAiLoadingAnimation()
  
  const loading = ElLoading.service({
    lock: true,
    text: () => aiJudgingText.value,
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
    customClass: 'ai-judging-loading'
  })
  
  try {
    const res = await userSubmitByAiService(submitDTO)
    loading.close()
    const aiResult = res.data
    // 展示结构化的AI判题结果对话框
    showAiResultDialog(aiResult)
  } catch (error) {
    loading.close()
    console.error('AI判题错误详情:', error)
    if (error.response && error.response.status === 503) {
      ElMessage.error('后端服务暂时不可用(503)，请确认后端服务是否正常运行')
    } else if (error.message && error.message.includes('timeout')) {
      ElMessage.error('AI判题请求超时，请稍后再试')
    } else {
      ElMessage.error(`AI判题请求失败: ${error.message || '未知错误'}`)
    }
  } finally {
    // 无论成功或失败，都停止动画并取消按钮的加载状态
    stopAiLoadingAnimation()
    aiJudgingLoading.value = false
  }
}

// AI判题结果对话框相关变量
const aiDialogVisible = ref(false)
const aiResultData = ref({
  isSuccess: false,
  message: ''
})

// 处理AI判题结果消息，将代码部分提取出来
function processAiMessage(message) {
  if (!message) return { content: '', codes: [] }
  
  // 新的返回消息格式
  let content = '';
  const codes = [];
  
  // 检查消息是否包含代码示例
  if (message.includes('class Solution') || message.includes('public int[]')) {
    // 分割文本和代码部分
    const parts = message.split(/class Solution/);
    
    // 提取文本内容
    content = parts[0].trim();
    
    // 提取代码部分
    if (parts.length > 1) {
      const codeText = 'class Solution' + parts[1];
      
      // 寻找代码的结束位置
      let endIndex = codeText.indexOf('正确代码算法提示');
      if (endIndex === -1) {
        endIndex = codeText.length;
      }
      
      // 提取完整代码
      const code = codeText.substring(0, endIndex).trim();
      codes.push(code);
      
      // 如果有算法提示，也添加到内容中
      if (endIndex < codeText.length) {
        content += '<br><br>' + codeText.substring(endIndex).trim();
      }
    }
  } else {
    // 如果没有检测到代码块，将整个消息作为文本内容
    content = message;
  }
  
  return { 
    content: content,
    codes: codes 
  }
}

// 格式化AI内容，增强可读性
function formatAiContent(content) {
  if (!content) return ''
  
  // 替换换行符为<br>，但减少多余的空行
  let formatted = content.replace(/\n\n+/g, '\n\n').replace(/\n/g, '<br>');
  
  // 为各种分析部分添加样式
  formatted = formatted.replace(/(代码问题分析：|代码出错分析：|正确代码算法提示：)/g, '<div class="ai-section-header">$1</div>');
  
  // 为各种具体问题添加样式
  formatted = formatted.replace(/(时间复杂度过高|未采用更高效算法|哈希表法|双指针法)/g, '<div class="ai-subsection-header">$1</div>');
  
  return formatted;
}

// 复制代码到剪贴板
function copyCode(code) {
  navigator.clipboard.writeText(code).then(() => {
    ElMessage.success('代码已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 显示AI判题结果对话框
function showAiResultDialog(aiResult) {
  aiResultData.value = aiResult
  aiDialogVisible.value = true
}

// 根据分数返回对应的颜色
function getScoreColor(score) {
  if (score >= 80) return '#67C23A' // 绿色 - 优秀
  if (score >= 60) return '#E6A23C' // 橙色 - 良好
  return '#F56C6C' // 红色 - 需要改进
}

// 根据分数返回评价文字
function getScoreComment(score) {
  if (score >= 80) return '优秀的代码实现'
  if (score >= 60) return '代码实现基本正确，有改进空间'
  return '代码需要较大改进'
}

async function getQuestionResult() {
  const res = await getQuestionResultService(submitDTO.examId, submitDTO.questionId, currentTime)
  userQuestionResultVO.value = res.data
  if (userQuestionResultVO.value.pass !== 3) {
    stopPolling();
    // 判题完成后，检测是否需要水平滚动
    setTimeout(() => {
      checkScrollNeeded()
    }, 100)
  }
}

// 检测是否需要水平滚动
function checkScrollNeeded() {
  const rowValues = document.querySelectorAll('.row-value');
  rowValues.forEach(el => {
    if (el.scrollWidth > el.clientWidth) {
      el.style.overflowX = 'auto';
    } else {
      el.style.overflowX = 'hidden';
    }
  });
}

// 未通过测试用例详情对话框相关变量
const badCaseDialogVisible = ref(false)

function showBadCaseDialog() {
  badCaseDialogVisible.value = true
}

// 在script部分添加新的变量和方法
const fullContentDialogVisible = ref(false)
const fullContentText = ref('')
const fullContentTitle = ref('')

// 显示单元格完整内容
function showFullContent(content, title) {
  fullContentText.value = content
  fullContentTitle.value = title
  fullContentDialogVisible.value = true
}

// 复制完整内容
function copyFullContent() {
  navigator.clipboard.writeText(fullContentText.value).then(() => {
    ElMessage.success('内容已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}

// 表格样式
const tableHeaderStyle = {
  background: '#f5f7fa',
  color: '#606266'
}

// 检查错误信息是否过长需要截断
const isMessageTruncated = computed(() => {
  if (!userQuestionResultVO.value.exeMessage) return false
  return userQuestionResultVO.value.exeMessage.length > 200
})

</script>

<style lang="scss" scoped>
.praticle-page {
  margin-top: -40px;

  .box_1 {
    background-color: rgba(240, 240, 240, 1);
    height: 60px;
    display: flex;
    align-items: center;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;

    /* 垂直居中 */

    .box_1 span {
      margin-right: 10px;
      /* 文字与图片之间的间距 */
    }

    .exam-time-countdown {
      margin: 0 0 0 400px;
    }

    .group_1 {
      display: flex;
      align-items: center;

      img {
        margin-right: 10px;
      }
    }

    .thumbnail_1 {
      width: 1px;
      height: 20px;
      margin: 20px 0 0 8px;
    }

    .label_4 {
      width: 26px;
      height: 26px;
    }

    .group_2 {
      display: flex;
      gap: 10px;
    }

    .group_3 {
      cursor: pointer;
      background-color: rgba(7, 126, 255, 0.1);
      border-radius: 0px 6px 6px 0px;
      width: 100px;
      height: 40px;
      margin: 10px 0 0 2px;
      font-size: 20px;

      display: flex;
      justify-content: center;
      align-items: center;
    }

    .ide-back {
      cursor: pointer;
      color: #999999;
    }

    .label_2 {
      width: 30px;
      height: 30px;
      margin: 15px 0 0 500px;
    }

    .label_3 {
      width: 30px;
      height: 30px;
      margin: 15px 70px 0 30px;
    }
  }
}

.page {
  background-color: rgba(247, 247, 247, 1);
  position: relative;
  height: 910px;
  overflow: hidden;

  .box_8 {
    position: relative;
    width: 100%;
    height: 1451px;
    margin-bottom: 1px;

    .group_12 {
      width: 100%;
      height: 64px;
      margin-top: 10px;

      .image-wrapper_1 {
        background-color: rgba(240, 240, 240, 1);
        border-radius: 10px 10px 0px 0px;
        height: 64px;
        width: 600px;
        margin: 0 10px 10px 0;
        display: flex;
        align-items: center;
        padding: 0 10px;

        .thumbnail_2 {
          width: 14px;
          height: 15px;
          margin: 0 10px 0 10px;
        }

        .question-nav {
          display: flex;
          align-items: center;
          margin-right: 15px;
          cursor: pointer;
          height: 36px;
          font-size: 15px;
          font-family: PingFangSC;
          color: #606266;
          
          &.nav-btn {
            transition: all 0.3s;
            padding: 0 12px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            
            &:hover {
              background-color: rgba(64, 158, 255, 0.1);
              color: #409EFF;
            }
            
            .el-icon {
              margin-right: 5px;
            }
          }
        }
        
        .navigation-container {
          display: flex;
          align-items: center;
          margin-left: 20px;
          padding-left: 20px;
          gap: 15px;
        }
        
        .nav-divider {
          height: 20px;
          width: 1px;
          background-color: #DCDFE6;
        }
        
        .ai-recommendation-container {
          display: flex;
          align-items: center;
          margin-left: 5px;
          
          .ai-recommendation-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 36px;
            font-weight: 500;
            transition: all 0.3s;
            
            .rec-icon {
              margin-right: 5px;
              display: flex;
              align-items: center;
            }
          }
        }
      }

      .image-wrapper_2 {
        background-color: rgba(240, 240, 240, 1);
        border-radius: 10px 10px 0px 0px;
        height: 64px;
        display: flex;
        align-items: center;
        flex: 1;
        /* 垂直居中 */

        .image_1 {
          width: 21px;
          height: 16px;
          margin: 0 10px 0 19px;
        }
      }
    }

    .group_13 {
      height: 904px;

      .box_3 {
        background-color: rgba(255, 255, 255, 1);
        border-radius: 10px;
        height: 765px;
        width: 600px;
        margin-right: 10px;

        .question-title {
          font-weight: bold;
          font-size: 28px;
          margin-top: 20px;
          margin-left: 20px;
          margin-bottom: 10px;
        }

        .question-limit {
          font-size: 18px;
          color: #abaeac;
          margin-left: 20px;
          margin-bottom: 10px;
        }

        .question-content {
          font-size: 20px;
          margin-left: 20px;
        }

        .group_6 {
          background-color: rgba(241, 241, 241, 1);
          width: 21px;
          height: 874px;
          justify-content: flex-center;
          margin: 10px 0 0 923px;

          .thumbnail_3 {
            width: 9px;
            height: 6px;
            margin: 10px 0 0 6px;
          }

          .group_7 {
            background-color: rgba(192, 192, 192, 1);
            width: 16px;
            height: 296px;
            margin: 10px 0 0 3px;
          }

          .thumbnail_4 {
            width: 9px;
            height: 6px;
            margin: 536px 0 10px 6px;
          }
        }
      }

      .group_14 {
        height: 904px;
        display: flex;
        flex-direction: column;
        width: calc(100vw - 663px);

        .group_8 {
          background-color: rgba(255, 255, 255, 1);
          border-radius: 10px;
          flex: 0.75; /* 减少代码编辑器占比，为执行结果留出更多空间 */

          .thumbnail_5 {
            width: 11px;
            height: 6px;
            margin: 31px 0 0 69px;
          }

          .block_1 {
            width: 21px;
            height: 710px;
            border: 1px solid rgba(241, 241, 241, 1);
            margin: 19px 0 0 923px;
          }

          .image_2 {
            width: calc(100vw - 663px);
            height: 1px;
            margin: -710px 0 763px 0;
          }
        }

        .code-result {
          background-color: rgba(240, 240, 240, 1);
          border-radius: 10px 10px 0px 0px;
          height: 64px;
          margin-top: 20px;
          width: calc(100vw - 663px);

          .code-result-image {
            width: 27px;
            height: 27px;
            margin: 24px 0 0 20px;
          }

          .code-result-content {
            margin: 26px 0 0 5px;
          }
        }
      }
    }

    .group_15 {
      width: calc(100vw - 663px);
      height: auto;
      min-height: 200px;
      
      .section_1 {
        background-color: rgba(255, 255, 255, 1);
        border-radius: 0px 0px 10px 10px;
        width: 100%;
        padding-bottom: 20px;

        .section_3 {
          width: 95%;
          height: auto;
          padding: 24px 20px;
          overflow-y: auto;
          max-height: 380px;
        }
      }
    }
  }
}

.dialog-footer {
  display: block;
  text-align: right;
  /* 确保内容右对齐 */
  margin-top: 16px;

  .dialog-button {
    width: 150px;
  }
}

.ai-result-dialog {
  :deep(.el-dialog__body) {
    max-height: 70vh;
    overflow-y: auto;
    padding: 20px;
  }
  
  .ai-result-content {
    line-height: 1.6;
    
    .ai-result-header {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      padding: 15px;
      border-radius: 4px;

      &.success {
        background-color: rgba(103, 194, 58, 0.1);
        border-left: 4px solid #67c23a;
      }
      
      &.failure {
        background-color: rgba(245, 108, 108, 0.1);
        border-left: 4px solid #f56c6c;
      }

      .el-icon {
        margin-right: 10px;
        font-size: 24px;
      }

      span {
        font-size: 18px;
        font-weight: bold;
      }

      .error-message {
        color: #F56C6C;
        margin-left: 10px;
        font-weight: normal;
        font-size: 14px;
        background-color: rgba(245, 108, 108, 0.05);
        padding: 4px 8px;
        border-radius: 4px;
      }
    }

    .ai-analysis-section {
      margin-bottom: 20px;

      .section-title {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        
        i {
          margin-right: 8px;
          color: #409eff;
        }
      }

      .ai-text-content {
        white-space: pre-wrap;
        background-color: #f8f9fa;
        padding: 15px;
        border-radius: 4px;
        border: 1px solid #ebeef5;
        
        :deep(.ai-section-header) {
          font-size: 18px;
          font-weight: bold;
          color: #409eff;
          margin: 10px 0 5px 0;
        }
        
        :deep(.ai-subsection-header) {
          font-size: 16px;
          font-weight: bold;
          color: #303133;
          margin: 8px 0 4px 0;
        }
      }
    }
    
    .ai-code-blocks {
      .section-title {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        
        i {
          margin-right: 8px;
          color: #409eff;
        }
      }
      
      .code-block {
        margin-bottom: 20px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        padding: 16px;
        background-color: #f8f9fa;
        
        .code-title {
          font-weight: bold;
          margin-bottom: 12px;
          font-size: 16px;
          color: #303133;
          border-bottom: 1px dashed #dcdfe6;
          padding-bottom: 8px;
        }
        
        .code-content {
          background-color: #f5f7fa;
          border-radius: 4px;
          padding: 16px;
          font-family: Consolas, Monaco, 'Andale Mono', monospace;
          font-size: 14px;
          white-space: pre;
          overflow-x: auto;
          line-height: 1.5;
          border: 1px solid #e6e6e6;
        }

        .copy-code-btn {
          margin-top: 10px;
        }
      }
    }

    .ai-score-section {
      margin-top: 20px;
      padding: 20px;
      background-color: #f8f9fa;
      border-radius: 4px;
      border: 1px solid #ebeef5;

      .section-title {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        
        i {
          margin-right: 8px;
          color: #E6A23C;
        }
      }

      .score-display {
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .score-text {
          margin-left: 30px;
          display: flex;
          flex-direction: column;

          span {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
          }

          .score-comment {
            font-size: 14px;
            color: #606266;
          }
        }
      }
    }
  }
}

/* AI判题加载样式 */
:deep(.ai-judging-loading) {
  .el-loading-spinner {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .circular {
      width: 50px;
      height: 50px;
    }
    
    .el-icon-loading {
      font-size: 30px;
      animation: pulse 2s infinite;
    }
    
    .el-loading-text {
      font-size: 16px;
      margin-top: 10px;
      color: #fff;
      animation: fadeInOut 1.5s infinite;
      
      &::before {
        content: '🤖 ';
        font-size: 20px;
        margin-right: 5px;
      }
    }
    
    &::after {
      content: '大模型分析中，请稍候...';
      display: block;
      font-size: 14px;
      margin-top: 12px;
      color: rgba(255, 255, 255, 0.8);
      animation: fadeIn 0.5s ease-in;
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes fadeInOut {
  0% {
    opacity: 0.7;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.7;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.similar-question-btn {
  position: relative;
}

.recommendation-btn {
  position: relative;
  display: flex;
  align-items: center;
  padding: 0 12px;
  cursor: pointer;
  transition: all 0.3s;
  overflow: visible;
  min-width: 120px;
  height: 32px;
  white-space: nowrap;
}

.recommendation-btn:hover {
  color: #67c23a;
  transform: translateY(-1px);
}

.recommendation-btn.is-loading {
  pointer-events: none;
}

.pulse-effect {
  position: absolute;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #67c23a;
  right: -8px;
  top: 50%;
  transform: translateY(-50%);
  box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  z-index: 10;
}

.loading-mask .is-loading {
  font-size: 20px;
  color: #409eff;
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  100% {
    transform: rotate(360deg);
  }
}

.recommendation-btn .rec-icon {
  display: flex;
  align-items: center;
  margin-right: 4px;
}

.recommendation-btn .rec-text {
  white-space: nowrap;
  font-size: 14px;
}

// 添加AI相似题目加载对话框样式
.similar-loading-dialog {
  :deep(.el-dialog__header) {
    padding: 20px;
    margin-right: 0;
    text-align: center;
    font-weight: bold;
  }
  
  :deep(.el-dialog__body) {
    padding: 30px 20px;
  }
  
  .loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    
    .loading-icon {
      font-size: 50px;
      color: #409EFF;
      animation: rotating 2s linear infinite;
    }
    
    .loading-text {
      font-size: 18px;
      font-weight: bold;
      margin: 20px 0 10px;
    }
    
    .loading-subtext {
      font-size: 14px;
      color: #909399;
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}

// 添加无相似题目对话框样式
.no-similar-dialog {
  :deep(.el-dialog__header) {
    padding: 20px;
    margin-right: 0;
    text-align: center;
    font-weight: bold;
  }
  
  :deep(.el-dialog__body) {
    padding: 20px;
  }
  
  .no-similar-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    
    .info-icon {
      font-size: 40px;
      color: #E6A23C;
      margin-bottom: 20px;
    }
    
    .info-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    
    .info-reasons {
      text-align: left;
      width: 100%;
      background-color: #FDF6EC;
      padding: 15px;
      border-radius: 4px;
      
      p {
        font-weight: bold;
        margin-bottom: 10px;
      }
      
      ul {
        padding-left: 20px;
        
        li {
          margin-bottom: 8px;
          color: #606266;
        }
      }
    }
  }
}

// 新的执行结果样式
.result-container {
  width: calc(100vw - 663px);
  background-color: #FFFFFF;
  border-radius: 0 0 10px 10px;
  padding: 12px;
  height: 350px; /* 减少高度，因为表格布局较紧凑 */
  display: flex;
  flex-direction: column;
  
  .result-header {
    margin-bottom: 10px;
    
    .result-status {
      font-size: 16px;
      font-weight: 500;
      
      &.red { color: #F56C6C; }
      &.success { color: #67C23A; }
      &.warning { color: #E6A23C; }
      &.info { color: #409EFF; }
    }
  }
  
  // 未通过情况样式
  .fail-result {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .error-info {
      margin-bottom: 15px;
      padding: 8px 12px;
      background-color: rgba(245, 108, 108, 0.1);
      border-left: 3px solid #F56C6C;
      border-radius: 0 4px 4px 0;
      max-height: 120px;
      overflow-y: auto;
      
      .error-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        
        .error-title {
          font-weight: bold;
          color: #303133;
          font-size: 12px;
        }
        
        .error-view-btn {
          padding: 4px 8px;
          font-size: 11px;
          height: 24px;
          line-height: 1;
        }
      }
      
      .error-message {
        position: relative;
        
        .error-text {
          color: #F56C6C;
          font-family: Consolas, Monaco, monospace;
          font-size: 12px;
          line-height: 1.4;
          
          &.error-text-truncated {
            max-height: 60px;
            overflow: hidden;
            position: relative;
            
            &::after {
              content: '';
              position: absolute;
              bottom: 0;
              left: 0;
              width: 100%;
              height: 20px;
              background: linear-gradient(transparent, rgba(245, 108, 108, 0.05));
            }
          }
        }
        
        .show-more-btn {
          margin-top: 8px;
          padding: 2px 6px;
          font-size: 10px;
          height: 20px;
          line-height: 1;
        }
      }
    }
    
    .fail-summary {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #FDF6EC;
      padding: 12px 15px;
      border-radius: 4px;
      margin: 10px 0;
      
      .summary-text {
        color: #E6A23C;
        font-weight: bold;
        font-size: 14px;
      }
      
      .view-details-btn {
        margin-left: 20px;
      }
    }
  }
  
  // 通过情况表格样式
  .success-result {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .success-table {
      flex: 1;
      overflow: auto;
      
      :deep(.el-table) {
        height: 100%;
        
        .el-table__header-wrapper {
          th {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: 600;
            padding: 8px 0;
          }
        }
        
        .el-table__row {
          td {
            padding: 5px 0;
            font-size: 12px;
          }
        }
      }
    }
  }
  
  // 空状态或加载状态样式
  .empty-result {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .loading-icon {
      font-size: 24px;
      color: #409EFF;
      margin-bottom: 10px;
      animation: rotating 2s linear infinite;
    }
    
    .empty-text {
      color: #909399;
      font-size: 14px;
    }
  }
}

// 未通过测试用例详情对话框样式
.bad-cases-container {
  max-height: 60vh;
  overflow-y: auto;
  padding: 5px;
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: #f8f8f8;
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #dcdfe6;
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-thumb:hover {
    background: #c0c4cc;
  }
  
  .bad-case-card {
    background-color: #FFFFFF;
    border: 1px solid #EBEEF5;
    border-radius: 4px;
    margin-bottom: 10px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &.case-failed {
      border-left: 3px solid #F56C6C;
    }
    
    .case-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 12px;
      border-bottom: 1px solid #EBEEF5;
      background-color: #f8f9fa;
      
      .case-number {
        font-weight: bold;
        font-size: 14px;
        color: #303133;
      }
    }
    
    .case-content {
      padding: 10px 12px;
      
      .case-row {
        margin-bottom: 10px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .row-label {
          font-weight: bold;
          margin-bottom: 4px;
          font-size: 13px;
          color: #606266;
          display: flex;
          align-items: center;
        }
        
        .row-value {
          background-color: #F5F7FA;
          padding: 6px 10px;
          border-radius: 4px;
          font-family: Consolas, Monaco, 'Andale Mono', monospace;
          font-size: 13px;
          line-height: 1.4;
          min-height: 30px;
          max-height: 150px;
          white-space: pre-wrap;
          word-break: break-all;
          overflow-x: auto;
          overflow-y: auto;
          
          &::-webkit-scrollbar {
            height: 5px;
            width: 5px;
          }
          
          &::-webkit-scrollbar-track {
            background: #f8f8f8;
            border-radius: 2px;
          }
          
          &::-webkit-scrollbar-thumb {
            background: #dcdfe6;
            border-radius: 2px;
          }
          
          &::-webkit-scrollbar-thumb:hover {
            background: #c0c4cc;
          }
          
          &.input-value {
            background-color: #F0F9EB;
          }
          
          &.output-error {
            background-color: rgba(245, 108, 108, 0.1);
            color: #F56C6C;
          }
        }
      }
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}

// 添加单元格内容样式
.cell-content {
  cursor: pointer;
  position: relative;
  
  &:hover {
    color: #409EFF;
    text-decoration: underline;
  }
  
  &::after {
    content: '🔍';
    position: absolute;
    right: -18px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 12px;
    opacity: 0;
    transition: opacity 0.2s;
  }
  
  &:hover::after {
    opacity: 1;
  }
}

// 添加完整内容对话框样式
.full-content-dialog {
  .full-content-container {
    max-height: 50vh;
    overflow: auto;
    background-color: #f8f9fa;
    border-radius: 4px;
    padding: 10px;
    border: 1px solid #ebeef5;
    
    .full-content-text {
      white-space: pre-wrap;
      word-break: break-word;
      font-family: Consolas, Monaco, monospace;
      font-size: 14px;
      line-height: 1.5;
      margin: 0;
    }
  }
}
</style>